<template>
  <div class="activityarea-box">
    <div class="activity-banner-box">
      <img class="activity-img" src="./img/youren-banner.png" />
    </div>
    <!-- 搜索条件-->
    <div class="breadcrumb knife_container ">
      <!-- <router-link :to="{name: 'Index'}" class="bread_a">首页</router-link><i class="el-icon-arrow-right"></i> -->
      <span class="bread_a">全部结果</span> <i class="el-icon-arrow-right"></i>
        <!-- <el-tag size="mini" class="search-tags" v-for="(item, index) in searchTags" type="info" :key="index" v-if="item" @close="closeTag(index)" closable>{{item}}</el-tag> -->
        共 
      <em class="color-red">{{amount}}</em>件商品
    </div>
    <!-- 菜单列表 -->
    <section class="category-box" v-if="activityLen">
      <div class="category-item knife_container">
        <div class="category-row">
          <span class="category-tit">商品名称</span>
          <section class="category-cont" :class="[collapseCate ? '':'isActive']">
            <div class="collose-tag collose-pos" v-if="cateHeight > 60"
              @click="collapseCate = !collapseCate">{{collapseCate ? '收起':'展开'}}
              <i :class="[collapseCate ? 'el-icon-arrow-up':'el-icon-arrow-down']"></i>
            </div>
            <div class="cont-item" ref="refCategory">
              <a class="cont-item_a" :class="{'active': categoryIds === ''}"
              @click="categoryIds = '', categoryText = '', getAllData()">全部商品</a>
              <a v-for="(item, index) in categoryList" :key="index"
                @click="clickCondi(item.id, 1, item.name)"  class="cont-item_a" 
                :class="{'active': item.id === Number(categoryIds)}" :data-id="item.id" >
                {{item.name}}
              </a>
            </div>
          </section>
        </div>
        <!-- 属性 -->
        <div class="category-row" v-if="otherList.length > 0">
          <span class="category-tit">属性</span>
          <section class="category-cont" :class="[collapseOther ? '':'isActive']">
            <div class="collose-tag collose-pos" v-if="otherHeight > 60"  @click="collapseOther = !collapseOther">{{collapseOther ? '收起':'展开'}} <i :class="[collapseOther ? 'el-icon-arrow-up':'el-icon-arrow-down']"></i></div>
            <div class="cont-item brand-item" ref="refProperty">
              <a class="cont-item_a" :class="{'active': othersIds === ''}"
                @click="othersIds = '', othersText = '', getAllData()">全部属性</a>
              <a class="cont-item_a" v-for="(otherItem, index) in otherList" :key="index"
              :class="{'active': otherItem === othersIds}" @click="clickCondi(otherItem, 2, otherItem)">{{otherItem}}</a>
            </div>
          </section>
        </div>
      </div>
    </section>
    <!-- !activityLen -->
    <div class="activity-product-body knife_container">
      <div v-if="!activityLen" class="search-box">
          <img src="../../../images/data_no.png" width="180px" style="margin-bottom: 30px;" alt="">
          <p class="search-notice">抱歉，暂未找到<span v-if="keyword">与“{{keyword}}”</span>相关商品，<span class="color-blue pointer" @click="clearCondi(), getAllData()">查看活动商品</span></p>
          <!-- <span class="search-result" @click="keyword = '', getAllData()">重新查找商品</span> -->
      </div>
      <div v-else>
        <ul class="list-wrapper">
          <li class="goods-item-border" v-for="(goodsItem, goodsIndex) in activityList" :key="goodsIndex">
            <div class="product-list-item">
              <div class="goods-image">
                <router-link 
                :to="{name: 'productDetail', params: {commodityID: goodsItem.id}}" target='_blank'>
                  <img class="list-img" :src="prefixImg + goodsItem.image" :alt="goodsItem.name"  @error="catchErrorImage($event)">
                </router-link>
              </div>
              <div class="goods-info">
                <router-link
                :to="{name: 'productDetail', params: {commodityID: goodsItem.id}}"
                class="goods-detail" v-html="goodsItem.name"></router-link>
                <p class="goods-other">{{goodsItem.other}}</p>
                <div class="goods-price">
                  <template v-if="isExamComputed === 1">
                    <span class="pro-price color-red">
                      {{goodsItem.priceLowerLimit| floatPrices}}
                      <template v-if="goodsItem.priceLowerLimit !== goodsItem.priceUpperLimit"> - {{goodsItem.priceUpperLimit | floatPrices}}</template>
                      元
                    </span>
                  </template>
                  <span class="pro-price smallfont color-red" v-else-if="isExamComputed === 4">登录后查看</span>
                  <span class="pro-price smallfont color-red" v-else>审核通过后查看</span>
                </div>
              </div>
              <div class="goods-right-order">
                <!-- <el-button type="primary" size="medium" class="goods-btn-add" @click="flodSku(goodsItem.id, goodsIndex)">{{showList[goodsIndex] ? '收起': '选择商品'}}</el-button> -->
                <span @click="flodSku(goodsItem.id, goodsIndex)" :class="{'rotate': showList[goodsIndex], 'select-arrow': true}"></span>
              </div>
            </div>

            <div class="sku-list-box" v-if="showList[goodsIndex]" :ref="`skuBox_${goodsIndex}`">
              <div class="sku-num-box bor-bt" >
                <span class="goods-name">共(<span class="color-red">{{(skuList[goodsIndex] && skuList[goodsIndex].length) || 0 }}</span>)款型号</span>
                <!-- v-if="skuList[goodsIndex] && skuList[goodsIndex].length > 8"-->
                <div class="commodity-search" v-if="totalRecordsList[goodsIndex] && totalRecordsList[goodsIndex] > 8">
                  <input type="text" v-model="searchList[goodsIndex]" placeholder="搜索" @keydown.enter="chooseCommodity(goodsItem.id, goodsIndex, true)"/>
                  <span class="searchBtn" @click="chooseCommodity(goodsItem.id, goodsIndex, true)"><i class="el-icon-search"></i></span>
                </div>
              </div>
              <!-- 规格列表 -->
              <ul class="sku-show-list-ul">
                <li v-if="!(skuList[goodsIndex] && skuList[goodsIndex].length)" class="no-content">
                  没有搜到相关的型号
                </li>
                <template v-for="(skuItem, skuIndex) in skuList[goodsIndex]" v-else>
                  <li class="goods-item-border sku-list-item bor-bt" :key="skuIndex">
                    <span class="goods-info ellipsis">
                      {{skuItem.detail}}
                    </span>

                    <div class="goods-price">
                      <template v-if="isExamComputed === 1">
                        <span class="current-price">¥{{skuItem.price | floatPrices}}</span>
                      </template>
                      <span class="current-price" v-else-if="isExamComputed === 4">登录后查看</span>
                      <span class="current-price" v-else>审核通过后查看</span>
                    </div>
                    
                    <div class="goods-right-order">
                      <span class="sku-stock-status">（库存正常）</span>
                      <!-- @change="limitProNum($event, skuIndex, skuItem.packingNum, skuItem)" -->
                      <!-- :disabled="(skuItem.supplyModeCode !== 1 && skuItem.inventoryStatus === 3) ||isExamComputed !==1 " -->
                      <div class="sku-stock-box">
                        <el-input-number
                          class="goods-input-number"
                          @keydown.110.native.prevent="" 
                          size="mini "
                          :key="skuItem.id"
                          v-model="skuItem.number"
                          :min="0"
                          :max="skuItem.maxNum"
                          :ref="`pro_${goodsIndex}_${skuIndex}`"
                          :step="skuItem.packingNum"
                          @change="limitProNum($event, goodsIndex, skuIndex, skuItem.packingNum)"
                          >
                        </el-input-number>
                        <p class="packnum">包装数：{{skuItem.packingNum}}</p>
                      </div>
                      
                      <span class="goods-btn-add"
                        @click="addToTempcart(skuItem.id, skuItem.number, goodsIndex, skuIndex)">确认</span>
                      <!-- <el-button type="primary" size="medium" class="goods-btn-add" @click="addToTempcart(skuItem.id, skuItem.number, goodsIndex, skuIndex)">确认</el-button> -->
                    </div>
                  </li>
                </template>
              </ul>
            </div>
          </li>
        </ul>

      <!-- 分页 -->
      <el-row v-if="goodsPro && goodsPro.totalPages > 1">
        <el-pagination class="page_box" background layout="total, prev, pager, next, ->" :current-page="goodsPro.page"
          :total="goodsPro.totalRecords - 0" :page-size="goodsPro.pageSize - 0" @current-change="handlePage" ></el-pagination>
      </el-row>
      </div>
    </div>
    <!-- <button @click="clearCart(3605)">clearCart</button> -->
    <!-- 预付和实付模式 -->
    <section class="tabs-paymode-box" :style="{'height': `${tabsHei}px`, marginTop: `-${tabsHei}px`}" ref="tabsBoxRef">
      <div class="tablist">
        <span :class="{'tab-item-active': payMode === 'advancePayment', 'tab-item': true}" @click="payMode = 'advancePayment'">
          预付模式
          <template v-if="(10000 - +yourenAmount) > 0">
            <p class="ft-12">还差{{ 10000 - +yourenAmount}}元可预付</p>
          </template>
        </span>
        <span :class="{'tab-item-active': payMode === 'actualPayment', 'tab-item': true}" @click="payMode = 'actualPayment'">实付模式</span>
      </div>
      <div class="tabcontent">
        <div class="tab-pane tabcontent-active">
          <div class="tab-pane-left">
            <template v-if="payMode === 'advancePayment'">
              <div class="procurement_progress">
                <div class="progress_tag">
                  <div class="dot">
                    <p class="top" style="color: transparent;">0</p>
                    <p class="amount">优刃</p>
                    <span class="status">还未购买</span>
                  </div>
                  
                  <div class="dot">
                    <p class="top">预付2000元</p>
                    <p class="amount">10000元 优刃</p>
                    <span class="status">单笔购买</span>
                  </div>
                  <div class="dot">
                    <p class="top">预付10000元</p>
                    <p class="amount">50000元 优刃</p>
                    <span class="status">单笔购买</span>
                  </div>
                </div>
                <div class="progress_arrow" :style="{left: barWidth+ '%' }">
                  <span class="symbol">￥</span><span class="ft-24 symbol">{{yourenAmount | floatPrices}}</span>
                  <p class="ft-12" v-if="(10000 - +yourenAmount) <= 0">(可预付{{(0.2 * yourenAmount).toFixed(2)}})</p>
                </div>
                <!-- :class="{'active': levelInfo.level > ind || levelInfo.level === 0}" :style="{'left':levelWidthArr[ind]}" -->
                <div class="progress_bar">
                  <div class="progress_fill" :style="{width: barWidth+ '%'}"></div>
                </div>
              </div>
            </template>
            <div class="actual-payment-box" v-else>
              <span class="text">小计:</span>
               <span class="money-icon">¥</span>
              <div class="actual-payment-text" v-html="calcStyle(yourenAmount)">
              </div>
            </div>
          </div>
          <div class="tab-pane-right">
            <button 
              :class="{'btn-noactive': +yourenAmount === 0, 'btn-active': true}"
              :disabled="+yourenAmount === 0"
              @click="showSelectGoods" >查看已选商品</button>
            <button
              :class="{'btn-noactive': (10000 - +yourenAmount) > 0 && payMode === 'advancePayment', 'btn-active': true}"
              :disabled="(10000 - +yourenAmount) > 0 && payMode === 'advancePayment'"
              @click="goToPay">{{payMode === 'advancePayment' ? '去结算' : '加入采购清单'}}</button>
          </div>
        </div>
      </div>
    </section>
    <!-- pop -->
    <!-- 已选商品 selectedYourenGoodsPopVisi-->
    <el-dialog title="查看已选商品" :visible="selectedYourenGoodsPopVisi" width="630px" class="selectedYourenWrapper" @close="closeYourenGoodsPopVisi" lock-scroll>
      <section class="purchaselist selectedYourenBox">
        <div class="good_infos">
          <div class="skus_box_detail" v-for="(skuItem, skuIndex) in tempCartList.productList" :key="skuIndex">
            <div class="pro_name ellipsis pointer" @click="linkGoodsDetail(skuItem.goodsId, skuItem.activity)">
              <span class="goods-name">{{skuItem.goodsName}}</span>
              <p class="pro-name">{{skuItem.productName}}</p>
            </div>
            <div class="pro_good_price">
              <p class="good_price">¥{{skuItem.productPrice | floatPrices}}</p>
            </div>
            <span class="good_amount">
              <el-input-number class="input-num-self"
                @keydown.110.native.prevent=""
                size="mini"
                v-model="skuItem.number"
                :min="1"
                :max="skuItem.stockLimit ? (skuItem.personalLimited ? skuItem.lastPersonalLimitNum : skuItem.stock) : 99999" 
                :step="skuItem.packingNum"
                :ref="`pro_${skuIndex}`" 
                @change="changeProNum(skuItem.productId, $event, skuIndex, skuItem.packingNum)">
              </el-input-number>
              <p class="packnum">包装数：{{skuItem.packingNum}}</p>
            </span>
            <span class="good_oprate el-icon-close" @click="deleteSku(skuIndex, skuItem.id)"></span>
          </div>
        </div>
      </section>
      <div class="selectedYouren-footer" slot="footer">
        小计: <span class="color-red">￥<em class="font-20">{{yourenAmount}}</em></span>
        <button
          :disabled="(10000 - +yourenAmount) > 0 && payMode === 'advancePayment'"
          :class="{'btn-pop-disabled': (10000 - +yourenAmount) > 0 && payMode === 'advancePayment', 'btn-pay': true}"
          @click="goToPay">{{payMode === 'advancePayment' ? '去结算' : '加入采购清单'}}</button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import product from './components/product'
import { Pagination, Row, Input, Button, InputNumber, Tabs, TabPane, Dialog } from 'element-ui'
import { getCategoryListByKeyword, getBrandListByKeyword, getOtherListByKeyword, getGoodsListByKeyword, getProSpecList, getUnloginProSpecList, changeSomeProNumber, clearCart, deleteCart } from '@/service/get-data'
import { mapActions, mapState } from 'vuex'
import { stock, prefixImg } from '@/tool/index'
import { getCookie } from '@/config/mUntils'
import _ from 'lodash'
import { throttle } from '@/tool/tool'

export default {
  components: {
    product,
    elPagination: Pagination,
    elRow: Row,
    elInput: Input,
    elButton: Button,
    elInputNumber: InputNumber,
    elTabs: Tabs,
    elTabPane: TabPane,
    elDialog: Dialog
  },
  data () {
    return {
      prefixImg,
      goodsPro: {
        page: 1, // 商品列表的页码
        number: 10 // 商品列表一页的数量
      },
      categoryText: '', // 选中名称的文字
      othersText: '', // 选中其他属性的文字
      collapseCate: false, // 分类是否展开
      collapseOther: false, // 其他属性是否展开
      // selectType: '', // 主选0为品牌，1为类目
      // goodsObj: {}, // 商品列表
      categoryList: [], // 类目列表
      categoryIds: '',
      brandList: [], // 品牌列表
      brandIds: '',
      amount: '',
      // goodsId: '', // 获取规格商品的id
      otherList: [],
      othersIds: '',
      cateHeight: '', // 类目的高度
      otherHeight: '', // 其他属性的高度
      activityList: null,
      // TODO: 优刃参数
      payMode: 'actualPayment', // advancePayment预付 actualPayment 实付
      // advanceAmount: 0, // 预付差额
      keyword: '', // 搜索关键字
      skuList: [], // 10个规格
      readySkuList: [],
      searchList: [], // 搜索列表
      showList: [],
      totalRecordsList: [],
      // barWidth: '50%',
      tempCartList: [], // 临时购物车优刃的值
      selectedYourenGoodsPopVisi: false,
      selectYourenIdArr: '', // 临时购物车优刃的id
      tabsHei: 220
    }
  },
  computed: {
    ...mapState({
      cartlist: state => state.shopcart.cartlist,
      shopcartnum: state => state.shopcart.shopcartnum,
      username: state => state.user.username
    }),
    procurementId () {
      const cartLen = this.cartlist && this.cartlist.length
      let id = cartLen > 1 ? this.cartlist[1]['id'] : 0
      return id
    },
    Token () {
      return getCookie('Token')
    },
    activityLen () {
      return this.activityList && this.activityList.length
    },
    isExamComputed () {
      return this.$store.getters.loginStatus
    },
    yourenAmount () {
      let len = this.cartlist && this.cartlist.length
      if (len <= 1) return '0.00'// 购物车数量小于
      let tempYourenCart = this.cartlist && this.cartlist[1] && this.cartlist[1]['productList']
      let amount = 0
      let selectedId = []
      tempYourenCart.map((tempItem, tempIndex) => {
        if (tempItem.brandName === '优刃') {
          amount += tempItem.number * tempItem.productPrice
          selectedId.push(tempItem.id)
        }
      })
      this.selectYourenIdArr = JSON.stringify(selectedId)
      let l = this.selectYourenIdArr.length
      this.selectYourenIdArr = this.selectYourenIdArr.substring(1, l - 1)
      return amount.toFixed(2)
    },
    barWidth () {
      let amount = +this.yourenAmount
      // let level = [0.50, 1.00] // 1W与 5W的等级位置
      if (!amount) {
        return '0'
      }
      if (amount > 50000) {
        return '100'
      }
      if (amount >= 0 && amount <= 10000) {
        return `${amount / 10000 * 50}`
      }
      if (amount > 10000 && amount <= 50000) {
        let wid = (amount - 10000) / 40000 * 100 / 2 + 50
        return +`${wid}` > 100 ? '100' : `${wid}`
      }
    }
  },
  methods: {
    ...mapActions(['fetchActivityId', 'fetchOpenActivity', 'fetchCartList']),
    stock () {
      return stock
    },

    // 通过关键字获取类目列表
    async fetchCategoryList () {
      let res = await getCategoryListByKeyword(this.keyword, this.brandIds, 0, this.othersIds, this.activityId)
      res = res.data
      if (res.resultCode && res.resultCode === 2000) {
        this.categoryList = res.data
      }
    },

    // 获取其他属性
    async fetchOtherListByKeyword () {
      let res = await getOtherListByKeyword(this.keyword, this.categoryIds, this.brandIds, 0, this.activityId)
      res = res.data
      if (res.resultCode && res.resultCode === 2000) {
        this.otherList = res.data
      }
    },

    // 通过关键字获取品牌列表
    async fetchBrandList () {
      let res = await getBrandListByKeyword('优刃')
      if (res.data.resultCode && res.data.resultCode === 2000) {
        this.brandList = res.data.data
        if (this.brandList.length) {
          this.brandIds = this.brandList[0]['id']
        }
        return new Promise((resolve, reject) => {
          resolve()
        })
      }
    },

    // 点击品牌或者分类
    clickCondi (id, type, text) {
      this.selectType = type
      if (type === 1) {
        this.categoryIds = id
        this.categoryText = text
      } else {
        this.othersIds = id
        this.othersText = text
      }
      this.getAllData()
    },

    // 优刃商品
    async fetchGoodsListByKeyword () {
      let isNewKeyword = this.searchedKey !== this.keyword
      let res = await getGoodsListByKeyword(this.goodsPro.page, this.goodsPro.number, this.keyword, this.categoryIds, this.brandIds, this.othersIds, isNewKeyword, this.username)
      res = res.data
      if (res.resultCode && res.resultCode === 2000) {
        this.activityList = [...res.data.list]
        Object.assign(this.goodsPro, res.data.page)
        this.amount = res.data.page.totalRecords
        this.searchedKey = this.searchInput
      }
    },
    // 商品列表分页
    handlePage (page) {
      this.goodsPro.page = page
      this.fetchGoodsListByKeyword()
      this._initList()
    },
    getAllData () {
      this.fetchGoodsListByKeyword()
      this.fetchCategoryList()
      this.fetchOtherListByKeyword()
    },
    clearCondi () {
      this.categoryText = ''
      this.othersText = ''
      this.categoryIds = ''
      this.brandIds = ''
      this.othersIds = ''
      this.keyword = ''
    },
    catchErrorImage (e) {
      e.target.src = require('img/newload.png')
    },

    // 货品规格列表
    async chooseCommodity (goodsId, index, isFilter = false) {
      let list = this.skuList
      let readyList = this.readySkuList
      let filterList = []
      let seachWord = this.searchList[index]
      if (isFilter && seachWord) {
        filterList = readyList[index].filter((item, index) => {
          return item.detail.indexOf(seachWord) > -1
        })
        this.$set(this.skuList, index, filterList)
        return
      }
      let res
      if (!this.Token) {
        res = await getUnloginProSpecList(goodsId, 1, 100000) // , this.searchList[index]
      } else {
        res = await getProSpecList(goodsId, 1, 100000)
      }
      res = res.data
      if (res.resultCode && res.resultCode === 2000) {
        list[index] = res.data.list
        // list[index]['totalSize'] = res.data.page.totalRecords
        list[index].forEach((skuItem, skuIndex) => {
          skuItem.number = skuItem.number || 0
        })
        this.totalRecordsList[index] = res.data.page.totalRecords
        this.skuList = [...list]
        this.readySkuList = [...list]
      } else {
        this.$message({
          message: '未获取规格列表'
        })
      }
    },

    // 规格内部搜索
    serchProList (id, searchInd) {
      console.log(id, searchInd)
      // this.searchList[searchInd] || ''
      this.chooseCommodity(id, searchInd)
    },

    // 折叠规格列表
    flodSku (id, index) {
      let skulist = this.skuList[index]
      let currentShow = this.showList[index]
      // this.showList[index] = !this.showList[index]
      this.$set(this.showList, index, !currentShow)
      if (currentShow) return
      // 为false的时候
      if (!currentShow && !skulist) {
        this.chooseCommodity(id, index)
      }
    },

    // 初始化
    _initList () {
      this.skuList = Array.from({length: 10})
      this.readySkuList = Array.from({length: 10})
      this.totalRecordsList = Array.from({length: 10})
      this.searchList = Array.from({length: 10})
      this.showList = Array.from({length: 10}, (v, k) => (false))
    },

    // 限购购物车
    limitProNum (value, goodsInd, skuIndex, step) {
      this.skuList = [...this.skuList] // 强制vue监听变化
      this.debounceLimitProNum(value, goodsInd, skuIndex, step)
    },

    debounceProNum () {
      this.debounceLimitProNum = _.debounce(function (value, goodsInd, skuIndex, step) {
        if (value === 0) return
        let vm = this
        let lastNum = value % step
        let leftNum = lastNum === 0 ? value : value - lastNum + step
        if (lastNum !== 0) {
          this.$nextTick(() => {
            vm.$refs[`pro_${goodsInd}_${skuIndex}`][0].setCurrentValue(leftNum)
          })
          vm.skuList[goodsInd][skuIndex]['number'] = leftNum // 加入临时已选规格
        }
      }, 100, {leading: true, trailing: false})
    },

    // 用户是否登录或认证通过
    authUserMethod () {
      if (!this.Token) {
        this.$confirm('此操作需要登录,是否前去登录', '提示').then(() => {
          this.$router.push({name: 'Login', query: { redirect: this.$route.fullPath }})
        }).catch(() => {
          // console.log('不去')
        })
        return false
      } else if (this.isExamComputed === 3) {
        this.$store.commit('EXAMNODO', true)
        return false
      } else if (this.isExamComputed === 2) {
        this.$store.commit('EXAMFAIL', true)
        return false
      } else if (this.isExamComputed === 0) {
        this.$message.error('您的企业信息还在审核中,商品不能加入购物车,我们尽快给您审核.')
        return false
      } else {
        return true
      }
    },

    // 批量加入
    async addToTempcart (id, num, goodInd, skuInd) {
      let result = this.authUserMethod()
      console.log(result)
      if (!result) {
        return
      }
      if (!num) return
      let str = ''
      str = `[${id}:${num}:0]`
      if (!str) return
      let res = await changeSomeProNumber(str, this.procurementId)
      if (res.data.resultCode && res.data.resultCode === 2000) {
        this.skuList[goodInd][skuInd]['number'] = 0
        this.fetchCartList() // 更新购物车列表
        this._initTempCart()
        this.$message('商品已添加到【已选商品】中，可在下方【查看已选商品】中查看')
      } else {
        this.$message.error(res.data.resultMsg || '网络错误')
      }
    },
    togglePayModeClick (tab, event) {
      console.log(tab, event)
    },

    // 删除购物车
    async clearCart (id) {
      let res = await clearCart(+id)
      if (res.data.resultCode && res.data.resultCode === 2000) {
        console.log(res.data.resultMes)
        this.fetchCartList()
      }
    },

    showSelectGoods () { // 查看已选优刃商品
      let len = this.cartlist && this.cartlist.length
      if (len === 1) {
        this.$message('请先选择优刃商品')
        return
      }
      this.selectedYourenGoodsPopVisi = true
    },

    // 去结算或 加入购物车
    goToPay () {
      const action = new Map([
        ['advancePayment', () => { this.goToBalance() }],
        ['actualPayment', () => { this.addToShopcart() }]
      ])
      let event = action.get(this.payMode)
      event.call(this)
    },

    // 去结算
    goToBalance () {
      console.log('预付')
      // 选中的ids字符串
      this.$store.commit('SELECTIDS', this.selectYourenIdArr)
      // mutations 选中的数组对象
      this.$store.commit('SELECTEDPROLIST', this.tempCartList['productList'])

      this.$router.push({name: 'OrderInfo', query: {dropPoint: false, pmtAmount: 0, yourenAmount: this.yourenAmount, paymode: 'advancepayment'}})
    },

    // 加入购物车
    async addToShopcart () {
      if (+this.yourenAmount === 0) {
        this.$message('请选择优刃商品')
        return
      }
      let list = this.tempCartList && this.tempCartList['productList']
      let str = ''
      for (let i in list) {
        if (list[i].number !== 0) {
          str += `[${list[i].productId}:${list[i].number}:0],`
        }
      }
      if (!str) return
      let res = await changeSomeProNumber(str)
      if (res.data.resultCode && res.data.resultCode === 2000) {
        this.selectedYourenGoodsPopVisi = false // 优刃无 关闭弹窗
        this.clearCart(this.procurementId)
      } else { // 数量超限
        console.error(res.data.resultMsg || '网络错误')
      }
    },

    _initTempCart () { // tempCartList
      let len = this.cartlist && this.cartlist.length
      if (len <= 1) return false// 购物车数量小于
      this.tempCartList = JSON.parse(JSON.stringify(this.cartlist[1]))
    },
        // 防抖 添加货物
    debounceInputAmount () {
      this.debouncePro = _.debounce(async function (id, value, skuIndex, packingNum) {
        let step = packingNum
        // 输入框里删除的情况下为undefined，处理方式为改为最低数量step
        if (value === undefined) {
          this.tempCartList['productList'][skuIndex]['number'] = step
          value = step
        }
        // 计算倍数
        let lastNum = value % step
        if (lastNum !== 0) {
          this.$message({
            message: `此商品盒装数${step}`
          })
        }
        let leftNum = lastNum === 0 ? value : value - lastNum + step
        // let curObj = this.tempCartList['productList'][skuIndex]

        this.tempCartList['productList'][skuIndex]['number'] = leftNum
        this.$set(this.tempCartList, skuIndex, leftNum)
        this.$nextTick(() => {
          this.$refs[`pro_${skuIndex}`][0].$refs.input.setCurrentValue(leftNum)
        })
        let str = ''
        str = `[${id}:${leftNum}:1]`
        if (!str) return
        let res = await changeSomeProNumber(str, this.procurementId)
        if (res.data.resultCode && res.data.resultCode === 2000) {
          this.fetchCartList()
        } else { // 数量超限
          console.error(res.data.resultMsg || '网络错误')
        }
      }, 300, {leading: true, trailing: false})
    },

    // 货品数量的修改 changeProNumber
    changeProNum (id, value, skuIndex, step) {
      this.debouncePro(id, value, skuIndex, step)
    },

    // 移除临时购物车的商品
    async deleteSku (index, goodsId) {
      let res = await deleteCart(goodsId)
      if (res.data.resultCode && res.data.resultCode === 2000) {
        this.fetchCartList()
        // this._initTempCart()
      }
      if (+this.yourenAmount === 0) { // 优刃商品被删除完 弹窗关闭
        this.selectedYourenGoodsPopVisi = false
      }
      this.tempCartList.productList.map((productItem, productIndex) => {
        if (productIndex === index) {
          this.tempCartList.productList.splice(index, 1)
          let resultSku = this.tempCartList.productList
          this.$set(this.tempCartList, this.tempCartList['productList'], resultSku)
        }
      })
    },

    closeYourenGoodsPopVisi () {
      this.selectedYourenGoodsPopVisi = false
    },

    // 小计的样式
    calcStyle (str) {
      if (!str) throw new Error('文本不能为空')
      let html = ''
      for (let i = 0, len = str.length; i < len; i++) {
        html += `<span class="${str[i] === '.' ? 'point' : ''}">${str[i]}</span>`
      }
      return html
    }
  },
  mounted () {
    this._initList()
    this._initTempCart()
    this.debounceProNum()
    this.fetchBrandList().then(() => {
      this.getAllData()
    })
    this.debounceInputAmount()
    let vm = this
    setTimeout(function () {
      let refTabsBox = vm.$refs.tabsBoxRef || null
      vm.tabsHei = vm.$refs.tabsBoxRef.clientHeight
      window.onscroll = throttle(function () {
        var clientH
        var scrollH
        var scrollT
        var bottomH
        if (document.documentElement) {
          clientH = document.documentElement.clientHeight
          scrollH = document.documentElement.scrollHeight
        } else if (document.body) {
          clientH = document.body.clientHeight
          scrollH = document.body.scrollHeight
        }
        scrollT = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop
        bottomH = scrollH - clientH - scrollT
        if (bottomH > 500 && scrollT > 500 && refTabsBox) {
          // submit_order
          refTabsBox.className = 'tabs-paymode-box tabs-paymode-fixed'
        } else if (refTabsBox) {
          refTabsBox.className = 'tabs-paymode-box'
        }
      }, 100)
    }, 2000)
  },
  beforeDestroy () {
    window.onscroll = ''
  },
  watch: {
    // 高度监测
    otherList () {
      setTimeout(() => {
        if (this.$refs.refProperty) {
          let height = this.$refs.refProperty.offsetHeight
          this.otherHeight = height
        }
      }, 1000)
    },
    categoryList (val) {
      setTimeout(() => {
        if (this.$refs.refCategory) {
          let height = this.$refs.refCategory.offsetHeight
          this.cateHeight = height
        }
      }, 1000)
    },
    cartlist (val) {
      this._initTempCart()
    }
  }
}
</script>

<style lang="scss" scoped>
  .activity-banner-box{
    position:relative;
    margin-bottom: 10px;
    // min-width: 1200px;
    // max-width: 1920px;
    text-align: center;
    // margin: 0 auto 76px;
    .activity-img{
      width:100%;
    }
  }
  .bread_a{
    position: relative;
    color: #333;
    &:after{
      position: absolute;
      content: '';
      width: 30px;
      height: 3px;
      background: #FDAE3F;
      border-radius: 2px;
      bottom: -4px;
      left: 50%;
      margin-left: -15px;
    }
  }
  .search-tags{
    margin-left: 5px;
    color: #333333;
    border: none;
    background: none;
  }
  .act-name-box{
    margin: 0 auto;
    width: 1200px;
    overflow: hidden;
    .act-item{
      width: 33.3%;
      line-height: 85px;
      text-align: center;
      font-size:28px;
      float: left;
      background: #E2E2E2;
      color: #999999;
      &.active{
        color: #333333;
        background: #fff;
      }
    }
  }
  // 分类 
  .category-box {
    position: relative;
    margin-top: 10px;
    .category-row{
      overflow: hidden;
      // display: flex;
      // border-bottom: 1px solid #e6e6e6;
      // justify-content: flex-start;
      transition: all 0.3s;
      background: #404040;
    }
    
    .category-tit {
      // display: table-cell;
      float: left;
      background: #404040;
      text-align: center;
      color: #ffffff;
      width:105px;
      line-height: 60px;
      font-size: 16px;
      border-bottom: 1px solid #404040;
    }
    .category-cont{
      position: relative;
      background: #fff;
      height: auto;
      /* margin-left: 90px; */
      float: left;
      width: 1085px;
      border-bottom: 1px solid #ececec;
    }
    .cont-item {
      // width: 1110px;
      //height: 60px;
      // line-height: 60px;
      border-bottom: 1px solid #e6e6e6;
      padding: 10px 150px 10px 0;
      &:last-child {
        border-bottom: none;
      }
    }
    .cont-item_a{
      color: #666;
      font-size: 14px;
      display: inline-block;
      padding: 13px 20px 13px 24px;
      &.active{
        color:#EE0000;
      }
    }
      .isActive{
      height: 60px;
      overflow: hidden;
    }
  }
  .collose-tag{
    font-size: 12px;
    color: #999;
    cursor: pointer;
    width: 60px;
    height: 30px;
    line-height: 30px;
    text-align: center;
  }
  .collose-pos{
    position: absolute;
    right: 10px;
    top: 10px;
  }
  .activity-product-body{
    margin-top: 20px;
    margin-bottom: 60px;
    padding-bottom: 220px;
  }
  .selected-tag{
    overflow: hidden;
    margin-bottom: 15px;
    color: #767676;
    font-size: 14px;
    height: 40px;
    line-height: 40px;
  }
  .selected-item{
    float: left;
    margin-right: 2px;
    cursor: pointer;
  }
  .show-time-box{
    position: relative;
    margin-top: -85px;
    background: #fff;
    margin-bottom: 20px;
    .act-show-box {
      padding: 36px 78px;
      font-size: 20px;
      color: #999999;
    }
    .count-down-box{
      display: inline-block;
      position: absolute;
      text-align: right;
      right: 78px;
      .red-notice{
        color:rgba(207,11,11,1);
        line-height:28px;
        font-size: 20px;
        margin-bottom: 10px;
        text-align: left;
        padding-left: 4px;
      }
    }
    .count-down-text{
      font-size:20px;
      line-height:28px;
      color: #999999;
      margin-top: 11.8px;
    }
  }
  .count-down-time{
    background:rgba(255,255,255,1);
    border:2px solid rgba(207,11,11,1);
    padding: 12px 11px;
    font-size: 0;
    .count-time{
      font-size: 59px;
      display: inline-block;
      width:58px;
      height:80px;
      background:rgba(207,11,11,1);
      line-height: 80px;
      color:rgba(255,255,255,1);
      text-align: center;
      margin-right: 4.6px;
      vertical-align: middle;
      &:last-child{
        margin-right: 0;
      }
    }
    .count-colon{
      font-size: 59px;
      padding: 0 10px 0 5px;
      color: #CF0B0B;
      vertical-align: middle;
      // margin: 0 -23px;
    }
    
  }
  .activity-over{
    font-size: 50px;
    color: #cf0b0b;
    padding: 20px 0;
    text-align: center;
  }
  .activity-over-text{
    color: #6B6B6B;
    font-size: 22px;
    margin-bottom: 47px;
  }
  .btn-pop-over{
    width:200px;
    height:50px;
    background:rgba(255,225,0,1);
    border-radius:5px;
    color:rgba(48,48,48,1);
    display: inline-block;
    line-height: 50px;
  }
  //搜索
  .activity-search-box{
    float: right;
    vertical-align: middle;
    position: absolute;
    right: 0;
    top: 0;
    width: 380px;
    height: 35px;
    line-height: 35px;
    background: rgba(235,235,235,1);
    border-radius: 20px;
    overflow: hidden;
    padding-left: 15px;
    .search_posi{
      font-size: 16px;
    }
    .search_input{
      width: 70%;
      font-size: 14px;
      background: rgba(235,235,235,1);
    }
    .search_sure{
      float: right;
      width: 87px;
      height: 35px;
      line-height: 37px;
      background: rgba(251,205,59,1);
      text-align: center;
      color: #333333;
      cursor: pointer;
    }
  }
  .search-box{
    margin: 160px 0;
    text-align: center;
    .search-img{
      margin-bottom: 30px;
    }
    .search-notice{
      color:rgba(51,51,51,1);
      font-size:16px;
      line-height:33px;
      margin-bottom: 20px;
    }
    .search-result{
      display: inline-block;
      width:300px;
      height:54px;
      line-height: 54px;
      background:rgba(255,204,0,1);
      border-radius:4px;
      color:rgba(68,68,68,1);
      text-align: center;
      cursor: pointer;
    }
  }

  .product-list-item{
    font-size: 0;
    padding: 20px 20px 20px 45px;
    position: relative;
    height: 120px;
    margin-top: 10px;
    background: #fff;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    border-bottom: 1px solid #f8f8f8;

    .goods-image{
      display: inline-block;
      vertical-align: top;
      width: 79px;
      height: 79px;
      border: 1px solid #e6e6e6;
      position: relative;
      img{
        width: 100%;
        // height: 90px;
      }
    }
    .goods-info{
      display: inline-block;
      vertical-align: top;
      width: 280px;
      margin: 0 120px 0 20px;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      .goods-detail{
        display: block;
        font-size: 16px;
        color: #333;
        margin-top: 5px;
        margin-bottom: 5px;
        // height: 20px;
        line-height: 20px;
        overflow: hidden;
      }
      .goods-other{
        font-size:14px;
        color: #666666;
        padding-bottom: 10px;
      }
      .goods-name{
        font-size: 12px;
        color: #888;
        margin: 5px 0;
      }
      .goods-price{
        display: inline-block;
        vertical-align: top;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        margin-top: 15px;
        font-size: 14px;
        .current-price{
          color: #FF0000;
          font-size: 16px;
        }
        .old-price{
          color: silver;
          font-size: 16px;
          text-decoration: line-through;
        }
      }
    }
    .goods-stock{
      display: inline-block;
      font-size: 14px;
      line-height: 16px;
      vertical-align: middle;
      margin-right: 20px;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
    }
    .goods-right-order{
      float: right;
      position: relative;
      display: inline-block;
      vertical-align: top;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      margin-top: 25px;
      font-size: 14px;
      
    }
    
    .select-arrow {
      position: relative;
      cursor: pointer;
      border: 8px solid transparent;
      border-top: 10px solid #666666;
      width: 0;
      height: 0;
      display: inline-block;
    }
    .rotate{
      transform: rotate(180deg);
    }
    .goods-input-number{
      width: 100px;
      margin-top: 3px;
      vertical-align: top;
    }
    .goods-right-packing{
      position: absolute;
      bottom: -18px;
      font-size: 12px;
      color: #B0B0B0;
    }
  }
  .sku-list-box{
    transition: all ease 0.3s;
    background: #fff;
  }
  .sku-show-list-ul{
    max-height: 334px;
    overflow-y: auto;
  }
  
  .sku-list-item{
    height: 66px;
    padding: 0 20px 0 40px;
    line-height: 66px;
    overflow: hidden;
    .goods-info {
      display: inline-block;
      width: 268px;
      float: left;
    }
    .goods-price{
      display: inline-block;
      font-size: 14px;
      color: #333333;
      float: left;
    }
    .goods-right-order{
      float: right;
    }
    .sku-stock-box{
      display: inline-block;
      line-height: 20px;
      text-align: center;
      vertical-align: middle;
      margin-right: 20px;
    }
    .sku-stock-status{
      vertical-align: middle;
      padding-right: 20px;
      font-size: 16px;
      color: #333;
    }
    
    .goods-btn-add{
      display: inline-block;
      line-height: 28px;
      text-align: center;
      width: 58px;
      border: 1px solid #ff0000;
      background: #fff;
      color: #ff0000;
      height: 28px;
      font-size: 14px;
      border-radius: 2px;
      cursor: pointer;
    }
  }
  .commodity-search{
    float: right;
    width: 250px;
    // margin-bottom: 10px;
    font-size: 14px;
    font-weight: 400;
    overflow: hidden;
    position: relative;
    input{
      width: 210px;
      padding-left: 10px;
      border: 1px solid #DBDBDB;
      height: 44px;
      line-height: 44px;
      border-radius: 4px 0 0 4px;
      box-sizing: border-box;
    }
    .searchBtn{
      position: absolute;
      right: 0px;
      top: 11px;
      font-size: 12px;
      text-align: center;
      display: inline-block;
      width: 45px;
      height: 45px;
      line-height: 45px;
      background-color: #FFCC00;
      color: #404040;
      font-weight: 600;
      cursor: pointer;
      border-radius: 0 4px 4px 0;
      font-size: 18px;
    }
  }
  .sku-num-box{
    padding: 0px 14px 0px 40px;
    height: 66px;
    line-height: 66px;
  }
  .packnum{
      font-size: 12px;
      color: #999;
    }
  .bor-bt{
    border-bottom: 1px solid #f8f8f8;
  }
  // 预付
  .tabs-paymode-box{
    position: relative;
    z-index: 55;
    width: 1190px;
    margin: 20px auto;
    box-shadow: none;
    border: none;
    background: transparent;
    .tablist{
      display: table;
      border-bottom: 1px solid #fff;
    }
    .tab-item{
      display: table-cell;
      width: 135px;
      height: 60px;
      vertical-align: middle;
      text-align: center;
      background: #FFE4E4;
      color:#FF9F9F;
      font-size: 14px;
      line-height: 18px;
      cursor: pointer;
    }
    .tab-item-active{
      background: #F35236;
      color: #fff;
    }
    .tabcontent{
      width: 100%;
      // height: 160px;
      background: #F35236;
      // padding: 18px 23px 20px 20px;
      // box-sizing: border-box;
    }
  }
  .tab-pane{
    display: flex;
    justify-content: space-between;
    padding: 18px 23px 20px 45px;
    height: 160px;
    box-sizing: border-box;
    align-items: center;
    .tab-pane-left{
      width:665px;
      height: 82px;
    }
    .tab-pane-right{
      float: right;
      button{
        border: none;
        width: 180px;
        height: 60px;
        border-radius: 6px;
        font-size: 16px;
        cursor: pointer;
        &:first-child{
          margin-right: 15px;
        }
      }
      .btn-active{
        background:linear-gradient(180deg,rgba(255,217,129,1) 0%,rgba(255,197,44,1) 100%);
        color: #333333;
      }
      .btn-noactive{
        background:rgba(255,255,255,1);
        color: #666666;
        cursor: not-allowed;
      }
    }
  }

  .tabs-paymode-fixed{
    position: fixed;
    bottom: 0;
    transform: translateX(-50%);
    left: 50%;
    z-index: 50;
    margin-bottom: 0;
  }
  
  .procurement_progress{
    position: relative;
    // margin-bottom: 28px;
    // height: 90px;
    .progress_tag{
      position: relative;
      // height: 90px;
      padding-top: 8px;
      line-height: 25px;
      .dot{
        position:absolute;
        display: inline-block;
        // margin-left: -10px;
        text-align: center;
        font-size: 12px;
        color: #fff;
        &:nth-child(1){
          left: 0%;
        }
        &:nth-child(2){
          left: 50%;
          margin-left: -47.5px;
        }
        &:nth-child(3){
          left: 85.5%;
          // margin-left: -47.5px;
        }
      }
      .top{
        margin-bottom: 24px;
      }
      .amount{
        border: 1px solid #fff;
        padding: 0 10px;
        line-height: 24px;
        height: 24px;

      }
      .discount{
        font-size:13px;
        color:rgba(255,255,255,1);
      }
    }
    .progress_arrow{
      position: absolute;
      left: 20px;
      bottom: -20px;
      max-width: 135px;
      text-align: center;
      background: #fff;
      color: #F35236;
      padding: 4px;
      box-sizing: border-box;
      transform: translateX(-50%);
      &:after{
        position: absolute;
        content: "";
        border: 8px solid transparent;
        border-top-color: #fff;
        bottom: -15px;
        left: 50%;
        margin-left: -8px;
      }
      .symbol{
        vertical-align: middle;
      }
    }
    .progress_bar{
      position: absolute;
      top: 38px;
      width: 100%;
      overflow: hidden;
      height: 10px;
      background: rgba(255,255,255,0.65);
    }
    .progress_fill{
      position: absolute;
      left: 0;
      top: 0;
      background: #FFF;
      /* border-radius: 7px; */
      width: 40%;
      height: 10px;
      z-index: 1;
    }
  }
  // 已选商品弹窗
  .purchaselist{
    // height: 220px;scroll
    max-height: 415px;
    // margin-bottom: 80px;
    overflow-y: auto;
  }
  .skus_box_detail{
    position: relative;
    border-bottom: 1px solid #f4f4f4;
    padding: 15px 0;
    box-sizing: border-box;
    &:last-child{
      border-bottom:none;
    }
    span{
      display: inline-block;
    }
    .pro_total_price{
      display: inline-block;
      vertical-align: middle;
      line-height: 25px;
      width: 15%;
      text-align: center;
      font-size: 16px;
    }
    .prefer-price{
      color: #474747;
      font-size: 12px;
    }
    .pro_name{
      width: 300px;
      display: inline-block;
      vertical-align: middle;
      // padding: 10px 0 10px 0;
      line-height: 1.5;
      .goods-name{
        color: #333333;
        font-size: 16px;
      }
      .pro-name{
        font-size: 14px;
        color: #666666;
      }
    }
    .good_price{
      color: #ff0000;
    }
    .good_amount{
      text-align: center;
      width: 20%;
      vertical-align: middle;
    }
  }
    .pro_good_price{
    display: inline-block;
    width: 12%;
    text-align:center;
    color: #666;
    font-size: 16px;
    vertical-align: middle;
    .pmt_price{
      line-height: 30px;
      color: #ff0000;
    }
    .old_price{
      line-height: 20px;
      color: #999;
      text-decoration: line-through;
      font-size: 12px;
    }
  }
  .good_oprate{
    position: relative;
    display: inline-block;
    width: 8%;
    text-align: right;
    cursor: pointer;
    z-index: 90;
    &:hover{
      color:#FFCC00
    }
  }
  .actual-payment-box{
    display: flex;
    justify-content: flex-start;
    align-items: center;
    color: #fff;
    margin-top: 17px;
    .text{
      font-size: 16px;
      padding-right: 10px;
    }
    .money-icon{
      padding-right: 8px;
    }
  }
  .selectedYourenWrapper{
    .btn-pay{
      width: 120px;
      position: absolute;
      background: #ffcc00;
      right: 0;
      height: 100%;
      top: 0;
      padding: 0 12px;
      text-align: center;
      line-height: 50px;
      border: none;
      cursor: pointer;
    }
    .btn-pop-disabled{
      background: #bdbdbd;
      color: #999;
    }
  }
  .font-20{
    font-size: 20px;
  }
</style>
<style lang="scss">
  .el-input-number--mini{
    width: 90px;
  }
  .el-input-number__increase, .el-input-number__decrease{
    background: #ffffff;
  }
  .el-input-number--mini .el-input__inner {
    padding-left: 30px!important;
    padding-right: 30px!important;
  }
  .selectedYourenWrapper{
    .el-dialog{
      border-radius: 10px;
      overflow: hidden;
    }
    .el-dialog__header{
      border-bottom: 1px solid #DBDBDB;
    }
    .el-dialog__title{
      color: #303030;
    }
    .el-dialog__footer{
      background: #f0f0f0;
      position: relative;
      height: 50px;
      line-height: 25px;
    }
    .selectedYouren-footer{
      text-align: left;
    }
  }
  .actual-payment-text{
    span{
      font-family: PingFangSC-Semibold;
      width: 50px;
      height: 50px;
      text-align: center;
      line-height: 50px;
      display: inline-block;
      background: #fff;
      font-size: 24px;
      color: #F35236;
      margin-right: 8px;
    }
    .point{
      font-weight: 600;
    }
  }
</style>

